//
//  NewAddressVC.m
//  sensen_ios
//
//  Created by mc on 16/2/26.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "NewAddressVC.h"


#import "BoyeChooseCityView.h"

#import "NewAddressCell.h"


#import "AddressModel.h"


@interface NewAddressVC ()<UITableViewDataSource,UITableViewDelegate,BoyeChooseCityViewDelegate,UITextFieldDelegate>{
    UITableView         *  _tableView;
    NSArray             *  _textArray;
    CityObject          * _cityObject;
    AddressModel        * _model;
    BOOL _isSelected;
}
@property (nonatomic,strong) NSMutableArray   *  dataArray;
@property (nonatomic,strong) BoyeChooseCityView     *  chooseCityView;


@end

@implementation NewAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 如果是第一条，则直接设是否设为默认地址的参数为yes
    _isSelected = self.isDefault ? YES : NO;
    
    self.title = @"添加地址";
    
    // 创建导航栏左边返回按钮
    [self createLeftBarButtonItemWithImagename:nil];

    [self buildTableView];
    
     [self buildChooseCity];
    
    _textArray = @[@"姓名",@"电话",@"详细地址",@"邮编"];
    _model = [[AddressModel alloc] init];
    
   
    

    // Do any additional setup after loading the view.
}

-(void)buildTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT- 64 - SCREEN_WIDTH / 8) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    _tableView.contentInset = UIEdgeInsetsZero;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = rgba(237, 238, 239, 1);
    [self buildAddView];
}



-(void)buildAddView{
   
    UIButton  * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, _tableView.bottom, SCREEN_WIDTH, SCREEN_WIDTH / 8);
    [self.view addSubview:saveBtn];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setBackgroundColor:SS_NAVI_BLUE_COLOR];
    
}


#pragma mark -- TableViewDelegate --

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 6;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row < 2) {
        static NSString * cellIdentifier = @"NewAddressCell";
        NewAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell ==nil) {
            cell = [[NewAddressCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.headLabel.hidden = YES;
            cell.textField.frame = CGRectMake(20, 0, cell.contentView.width - 50,cell.textField.height);
            //线
            [BoyeViewHandle defaultLineInView:cell.contentView];
            
        }

        cell.textField.placeholder = _textArray[indexPath.row];
        cell.textField.delegate = self;
        cell.textField.textColor = [UIColor darkGrayColor];
        cell.textField.tag = indexPath.row + 20;
        
        
        return cell;
    }
    
    else if (indexPath.row == 2){
        
        static NSString  * identifier = @"LabelView";
        UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier ];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.contentView.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 44);
            //省，市，区
            UILabel * label = [[UILabel alloc] init];
            label.frame = CGRectMake(20, 2, SCREEN_WIDTH - 20, 40);
            label.font = FONT(15);
            label.text = @"省市区";
            [cell.contentView addSubview:label];
            label.tag = 1001;
            label.textColor = [UIColor darkGrayColor];
            //tap
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseProvineCity:)];
            label.userInteractionEnabled = YES;
            [label addGestureRecognizer:tap];
            
            [BoyeViewHandle defaultLineInView:cell.contentView];

        }
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        return cell;

    }
    
    else if (indexPath.row > 2 && indexPath.row < 5){
        static NSString * cellIdentifier = @"NewAddressCell";
        NewAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell ==nil) {
            cell = [[NewAddressCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.headLabel.hidden = YES;
            cell.textField.frame = CGRectMake(20, 0, cell.contentView.width - 50,cell.textField.height);
            //线
            [BoyeViewHandle defaultLineInView:cell.contentView];
        }

        cell.textField.placeholder = _textArray[indexPath.row - 1];
        cell.textField.delegate = self;
        cell.textField.textColor = [UIColor darkGrayColor];
        cell.textField.tag = indexPath.row + 20;
        
        return cell;
    }
    
    
    static NSString  * identifier = @"LabelView";
    UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier ];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.contentView.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 44);
        //线
        [BoyeViewHandle defaultLineInView:cell.contentView];
    }
    
    UILabel * label = [[UILabel alloc] init];
    label.frame = CGRectMake(20, 2, SCREEN_WIDTH - 20, 40);
    label.font = FONT(15);
    label.text = @"设为默认地址";
    label.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:label];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [cell.contentView addSubview:button];
    button.tag = 1000;
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cell.contentView).offset(- 25);
        make.centerY.equalTo(cell.contentView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(15, 15));
        
    }];
    
    
    [button setBackgroundImage:[UIImage imageNamed:@"个人中心-管理收货地址详情1_07"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"个人中心-管理收货地址详情_07"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

    
    if (self.isDefault) {
        button.selected = YES;
        button.enabled = NO;
        [button setBackgroundImage:[UIImage imageNamed:@"个人中心-管理收货地址详情_07"] forState:UIControlStateNormal];
    }else{
        button.selected = NO;
    }
    /* 忽略点击效果 */
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return cell;

    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    if (indexPath.row == 5){
        if (self.isDefault) {
            [SVProgressHUD showOnlyStatus:@"首次添加自动为默认地址" withDuration:1];
            return;
        }
        UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
        UIButton * button = (UIButton *)[cell.contentView viewWithTag:1000];
        button.selected = !button.selected;
        _isSelected = button.selected;
    }
    
}


- (void)buttonAction:(UIButton *)button{
    button.selected = !button.selected;
    _isSelected = button.selected;
}




#pragma  mark --  保存 --
- (void)saveAction:(UIButton *)button{
    [self.view endEditing:YES];

     UserModel *user = [CommonCache getUserInfo];
     _model.uid = [user.uid integerValue];
    
    NSLog(@"________________%@", _model.contactname);
   
    if (!_model.contactname || _model.contactname.length == 0) {
        [SVProgressHUD showOnlyStatus:@"联系人为空" withDuration:1];
        return;
    }
    
    if (![BoyeTool isMobileUseable:_model.mobile]) {
        [SVProgressHUD showOnlyStatus:@"请输入正确的手机格式" withDuration:1];
        return;
    }
    
    
    if (!_model.mobile||_model.mobile.length == 0) {
        [SVProgressHUD showOnlyStatus:@"联系电话为空" withDuration:1];
        return;
    }

    if (!_model.pcaAddress || _model.pcaAddress.length == 0) {
        [SVProgressHUD showOnlyStatus:@"请选择省市区" withDuration:1];
        return;
    }

    if (!_model.detailinfo || _model.detailinfo.length == 0) {
        [SVProgressHUD showOnlyStatus:@"详细地址为空" withDuration:1];
        return;
    }

    
    if (_model.contactname && _model.mobile && _model.pcaAddress && _model.detailinfo) {
        [self requestAddUserAddress:_model];
    }else{
        return;
    }
    
}

#pragma mark  -- 新增收货地址接口  --
-(void) requestAddUserAddress:(AddressModel *)model{
    [SVProgressHUD showWithStatus:@"正在保存...."];
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    
    [diction setObject:[NSString stringWithFormat:@"%ld",(long)model.uid] forKey:@"uid"];
    [diction setObject:model.contactname forKey:@"contactname"];
    [diction setObject:model.mobile forKey:@"mobile"];
    [diction setObject:model.province forKey:@"province"];
    if (model.postal_code != nil && model.postal_code.length > 0) {
        [diction setObject:model.postal_code forKey:@"postal_code"];
    }else{
        [diction setObject:@"1"forKey:@"postal_code"];
    }
    [diction setObject:model.detailinfo forKey:@"detailinfo"];
    [diction setObject:model.city forKey:@"city"];
    [diction setObject:model.area forKey:@"area"];
    [diction setObject:model.provinceid forKey:@"provinceid"];
    [diction setObject:model.cityid forKey:@"cityid"];
    [diction setObject:model.areaid forKey:@"areaid"];
    [diction setObject:model.country forKey:@"country"];
    
    NSLog(@"城市ID*****************%@", diction[@"cityid"]);
    NSLog(@"区域ID*****************%@", diction[@"areaid"]);
    
    NSLog(@"城市*****************%@", diction[@"city"]);
    NSLog(@"区域*****************%@", diction[@"area"]);
    
    [BoyeHttpClient post:@"BY_Address_add" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        _model.address_id = [result integerValue];
        if (_isSelected) {
            [self requestSetDefaultAddress];
        }else{
            [SVProgressHUD showSuccessWithStatus:@"添加成功" withDuration:1];
            [self.navigationController popViewControllerAnimated:YES];

        }
    
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"地址添加%@", error);
         [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"保存失败，请重试"] withDuration:3];
    }];
}


#pragma mark  -- 设为默认地址接口--
-(void) requestSetDefaultAddress{
    
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_model.address_id] forKey:@"id"];
    
    [BoyeHttpClient post:@"BY_Address_setDefaultAddress" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"修改默认地址result:%@", result);
    
        [SVProgressHUD showSuccessWithStatus:@"默认地址修改成功" withDuration:1];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"默认地址修改失败，请重试"] withDuration:3];
    }];
}






#pragma  mark --  键盘下去 --
-(void)downKeyBoark{
    [self.view endEditing:YES];
    [_chooseCityView close];
    [self saveAction:nil];
}


// 创建城市选择器
-(void)buildChooseCity{
    
    _chooseCityView = [[BoyeChooseCityView alloc] initWithPicker];
    _chooseCityView.delegate = self;
    [self.view addSubview: _chooseCityView];
}


#pragma mark --  打开城市选择 --
-(void)chooseProvineCity:(UIGestureRecognizer *)recognizer{
    
    
    [_chooseCityView open];
    [self.view endEditing:YES];
    
    if (_model.pcaAddress.length == 0 ||_model.pcaAddress == nil||_model == nil) {
        _model.pcaAddress = @"北京市市辖区东城区";
        _model.area = @"东城区";
        _model.areaid = @"110101";
        _model.city = @"市辖区";
        _model.cityid = @"110100";
        _model.province = @"北京市";
        _model.provinceid = @"11000";
        _model.country = @"1017";
        UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
        UILabel * city = (UILabel *)[cell.contentView viewWithTag:1001];
        city.text = _model.pcaAddress;
        [self.dataArray replaceObjectAtIndex:2 withObject:_model.pcaAddress];
        
    }

}

#pragma mark ---- BoyeChooseCityView -----
-(void)chooseCityView:(BoyeChooseCityView *)chooseCity cityObject:(CityObject *)cityObject{
    
    DLog(@" -- %@ -- %@ - %@ - ",cityObject.city,cityObject.area,cityObject.province);
    
    _cityObject = cityObject;
    
    UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    UILabel * city = (UILabel *)[cell.contentView viewWithTag:1001];
    city.text = cityObject.pcaAddress;
    [self.dataArray replaceObjectAtIndex:2 withObject:cityObject.pcaAddress];
    
    
    _model.pcaAddress = [NSString stringWithFormat:@"%@%@%@",cityObject.province,cityObject.city,cityObject.area];
    _model.area = cityObject.area;
    _model.areaid = cityObject.areaid;
    _model.city = cityObject.city;
    _model.cityid = cityObject.cityid;
    _model.province = cityObject.province;
    _model.provinceid = cityObject.provinceid;
    _model.country = @"1017";
    
    
    if (cityObject.cityid == nil || cityObject.cityid.length == 0) {
        _model.cityid = @"0";
    }
    
    if (cityObject.areaid == nil || cityObject.areaid.length == 0) {
        _model.areaid = @"0";
    }
    if (cityObject.city == nil || cityObject.city.length == 0) {
        _model.city = @"0";
    }

    if (cityObject.area == nil || cityObject.area.length == 0) {
        _model.area = @"0";
    }
    

}



#pragma  mark --- textFieldDelegate ---

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [_chooseCityView close];
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    DLog(@" textfield   -*%@*-   ",textField.text);
    if (textField.tag != 10) {
        if (textField.text == nil) {
            textField.text = @"";
        }
        [self.dataArray  replaceObjectAtIndex:textField.tag-1 withObject:textField.text];
    }
    
    if (textField.tag == 20) {
        _model.contactname = textField.text;
    }
    else if (textField.tag == 21){
        _model.mobile = textField.text;
    }

    
    else if (textField.tag == 23) {
        _model.detailinfo = textField.text;
    }
    
    else if (textField.tag == 24){
        _model.postal_code = textField.text;
    }

    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
